/*
 * Script that sends requests to the server and
 * then routes responses to the correct handlers
 * 
 * Author: Chris Casola
 */


/**
 * Send a request to the server, it is assumed that the
 * request parameter is a javascript object that can
 * be turned into JSON
 */
function sendRequest(request) {
	XMLREQ = new xmlRequest(request);
	window.comm.send("/do", XMLREQ);
}

/**
 * Log error responses to the console
 */
function handleErrorResponse(response) {
	console.log("ERROR: " + JSON.stringify(response));
}

/**
 * Wrap the given request in a generic request
 * and set the request id.
 */
function xmlRequest(innerRequest) {
	this.__XMLclass = "request";
	this.version = "1.0";
	this.id = uuid.v4(); // generate unique request id
	this.__XMLchildren = [
		innerRequest
	];
}

/**
 * Pull each of the responses from the response array and
 * dispatch each to the responseHandler
 */
function parseResponse(response) {
	for (var i=0; i < response.length; i++) {
		responseHandler(response[i]);
	}
}

/**
 * Direct responses to the correct specialized handler
 */
function responseHandler(response) {
	if (response.success == "false") {
			console.log("Error occured");
			return;
	}
	console.log("Response: " + JSON.stringify(response));
	
	var dlResponse = response;
	
	if (typeof(dlResponse.createResponse) != "undefined") {
		handleCreateEventResponse(response);
	}
	else if (typeof(dlResponse.addChoiceResponse) != "undefined") {
		handleAddChoiceResponse(response);
	}
	else if (typeof(dlResponse.turnResponse) != "undefined") {
		// do nothing, we are keeping track of turns ourselves
	}
	else if (typeof(dlResponse.addEdgeResponse) != "undefined") {
		handleAddEdgeResponse(response);
	}
	else if (typeof(dlResponse.signInResponse) != "undefined") {
		handleSignInResponse(response);
	}
	else if (typeof(dlResponse.closeResponse) != "undefined") {
		handleForceCloseResponse(response);
	}
}
